package org.baizhiedu.cglib;

import org.baizhiedu.proxy.User;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * ClassName: TestCglib
 * Description:
 * Date: 2022/11/22 PM 2:31:18
 * <p>
 * project: spring5
 * package: org.baizhiedu.cglib
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class TestCglib {

    public static void main(String[] args) {
        // 1.创建原始对象
        UserService userService = new UserService();

        /*
        2.通过 cglib 方式创建动态代理对象
            Proxy.newProxyInstance(classloader, interface, invocationHandler)

            Enhancer.setClassLoader()
            Enhancer.setSuperClass()
            Enhancer.setCallback(); ---> MethodInterceptor(cglib)
            Enhancer.create() --> 代理
         */

        Enhancer enhancer = new Enhancer();

        enhancer.setClassLoader(TestCglib.class.getClassLoader());
        enhancer.setSuperclass(UserService.class);
        MethodInterceptor interceptor = (o, method, args1, methodProxy) -> {
            System.out.println("---cglib log---");
            return method.invoke(userService, args1);
        };
        enhancer.setCallback(interceptor);

        UserService userServiceProxy = (UserService) enhancer.create();
        userServiceProxy.login("suns", "123456");
        userServiceProxy.register(new User());
    }
}
